import EventEmitter from './eventemitter.js'

const CountdownStatus = {
  running: 'running',
  paused: 'paused',
  stoped: 'stoped'
}

export const CountdownEventName = {
  START: 'start',
  STOP: 'stop',
  RUNNING: 'running',
}


export function fillZero(num) {
  return `0${num}`.slice(-2)
}

const COUNT_IN_MILLISENCOND = 1 * 100;
const SECOND_IN_MILLISENCOND = 10 * COUNT_IN_MILLISENCOND;
const MINUTE_IN_MILLISENCOND = 60 * SECOND_IN_MILLISENCOND;
const HOUR_IN_MILLISENCOND = 60 * MINUTE_IN_MILLISENCOND;
const DAY_IN_MILLISENCOND = 24 * HOUR_IN_MILLISENCOND;

export class Countdown extends EventEmitter {

  constructor(endTime, step = 1e3) {
    super()
    this.endTime = endTime
    this.step = step
    this.remainTime = 0
    this.status = CountdownStatus.stoped
    setTimeout(() => {
      this.start()
    }, 0);
  }

  start() {
    this.emit(CountdownEventName.START)
    this.status = CountdownStatus.running
    this.countdown()
  }

  stop() {
    this.emit(CountdownEventName.STOP)
    this.status = CountdownStatus.stoped
  }

  countdown() {
    if (this.status !== CountdownStatus.running) return
    this.remainTime = Math.max(this.endTime - Date.now(), 0)
    console.log('111111111',this.remainTime)
    this.emit(CountdownEventName.RUNNING, this.parseRemainTime(this.remainTime), this.remainTime)
    if (this.remainTime > 0) {
      setTimeout(() => {
        this.countdown()
      }, this.step);
    } else {
      this.stop()
    }
  }

  parseRemainTime(remainTime) {
    let time = remainTime
    const days = Math.floor(time / DAY_IN_MILLISENCOND)
    time = time % DAY_IN_MILLISENCOND
    const hours = Math.floor(time / HOUR_IN_MILLISENCOND)
    time = time % HOUR_IN_MILLISENCOND
    const minutes = Math.floor(time / MINUTE_IN_MILLISENCOND)
    time = time % MINUTE_IN_MILLISENCOND
    const seconds = Math.floor(time / SECOND_IN_MILLISENCOND)
    time = time % SECOND_IN_MILLISENCOND
    const count = Math.floor(time / COUNT_IN_MILLISENCOND)
    return {
      days,
      hours,
      minutes,
      seconds,
      count
    }
  }
}